<template>
  <div>
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>预约挂号</el-breadcrumb-item>
        <el-breadcrumb-item>就诊纪录</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div style="margin-top: 20px">
      <el-tabs v-model="index" @tab-click="handleClick">
        <el-tab-pane label="进行中" name="0"></el-tab-pane>
        <el-tab-pane label="已完成" name="1"></el-tab-pane>
        <el-tab-pane label="已取消" name="2"></el-tab-pane>
      </el-tabs>
    </div>

    <div class="container" v-if="index === '0'">
      <div class="card" v-if="logList.length > 0">
        <el-row :gutter="50">
          <el-col :span="12"  v-for="(item,index) in logList"  >
            <div class="card-body" >

              <ul class="list-unstyled user-details list-unstyled-border list-unstyled-noborder">
                <li class="media">
                  <div class="media-body">
                    <div class="media-title <!--node-status node-is-offline-->">预约医生：{{item.name}}</div>
                    <div class="media-title <!--node-status node-is-offline-->">预约时间：{{item.appointmentDate  + '号' + item.slot}}</div>
                    <div class="media-title <!--node-status node-is-offline-->" v-if="item.detailDesc">具体症状：{{item.detailDesc}}</div>
                  </div>

                  <div class="media-items">
                    <div class="media-item">
                    <el-button round type="primary" @click="handleCancel(item)" style="margin-top: 10px;" >
                      取消预约
                    </el-button></div>
                    <div class="media-item">
                    <el-button round type="warning" @click="handleUpdate(item)" style="margin-top: 10px;" >
                      修改预约
                    </el-button>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
        <div style="text-align: center">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,6, 10]"
            :page-size="queryHaveParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="haveingTotal">
          </el-pagination>
        </div>
    </div>
      <div class="card" v-if="logList.length === 0">
        暂无数据
      </div>
    </div>
    <div class="container" v-if="index ===  '1'">
      <div class="card" v-if="completeList.length > 0">
        <el-row :gutter="50">
          <el-col :span="12"  v-for="(item,index) in completeList"  >
            <div class="card-body" >
            <ul class="list-unstyled user-details list-unstyled-border list-unstyled-noborder">
              <li class="media">
                <div class="media-body">
                  <div class="media-title <!--node-status node-is-offline-->">就诊医生：{{item.name}}</div>
                  <div class="media-title <!--node-status node-is-offline-->">就诊时间：{{item.appointmentDate  + '号' + item.slot}}</div>
                  <div class="media-title <!--node-status node-is-offline-->" v-if="item.opinion">就诊意见：{{item.opinion}}</div>
                </div>

                <div class="media-items">
                  <div class="media-item">
                    <el-button round type="primary" v-if="item.commentDef === '0'" @click="handlerEvaluate(item)" style="margin-top: 10px;" >
                      进行评价
                    </el-button>
                    <el-button round type="primary" v-if="item.commentDef === '1'" @click="viewEvaluate(item)" style="margin-top: 10px;" >
                      查看评价
                    </el-button>
                  </div>
                  <div class="media-item">
                    <el-button round type="warning" @click="showDetails(item)" style="margin-top: 10px;" >
                      查看就诊单
                    </el-button>
                  </div>
                </div>
              </li>
            </ul>
            </div>
          </el-col>
        </el-row>
        <div style="text-align: center;">
          <el-pagination
            @size-change="handleCompleteSizeChange"
            @current-change="handleCompleteCurrentChange"
            :current-page="currentCompletePage"
            :page-sizes="[3,6, 10]"
            :page-size="queryCompleteParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="completeTotal">
          </el-pagination>
        </div>

      </div>
      <div class="card" v-if="completeList.length === 0">
        暂无数据
      </div>
    </div>
    <div class="container" v-if="index === '2'">
      <div class="card" v-if="cancelList.length > 0">
        <el-row :gutter="50">
          <el-col :span="12"  v-for="(item,index) in cancelList"  >
            <div class="card-body" >
            <ul class="list-unstyled user-details list-unstyled-border list-unstyled-noborder">
              <li class="media">
                <div class="media-body">
                  <div class="media-title <!--node-status node-is-offline-->">预约医生：{{item.name}}</div>
                  <div class="media-title <!--node-status node-is-offline-->">预约时间：{{item.appointmentDate  + '号' + item.slot}}</div>
                  <div class="media-title <!--node-status node-is-offline-->" v-if="item.detailDesc">就诊意见：{{item.detailDesc}}</div>
                </div>
              </li>
            </ul>
            </div>
          </el-col>

        </el-row>
        <div style="    text-align: center;">
          <el-pagination
            @size-change="handleCancelSizeChange"
            @current-change="handleCancelCurrentChange"
            :current-page="currentCancelPage"
            :page-sizes="[3,6, 10]"
            :page-size="queryCancelParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="cancelTotal">
          </el-pagination>
        </div>
      </div>
      <div class="card" v-if="cancelList.length === 0">
        暂无数据
      </div>
    </div>

    <!-- 添加或修改友链对话框 -->
    <el-dialog title="修改预约" :visible.sync="open" width="500px" append-to-body>
      <el-form  v-loading="loading" ref="form" :model="form" label-width="auto">
        <el-form-item label="医生名称：">
          <el-input style="width: 300px" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="预约日期：">
          <el-col :span="11">
            <el-date-picker type="date"  value-format="yyyy-MM-dd" @change="changeDate" :picker-options="pickerOptions" placeholder="选择日期" v-model="form.appointmentDate" style="width: 300px;"></el-date-picker>
          </el-col>

        </el-form-item>
        <el-form-item label="预约时间段：">
          <el-select  style="width: 300px"  clearable v-model="form.slot" placeholder="请选择时间段">
            <el-option v-if="morning" label="上午" value="0"></el-option>
            <el-option v-if="afternoon" label="下午" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="具体症状描述：">
          <el-input style="width: 300px"  type="textarea" v-model="form.desc"></el-input>
        </el-form-item>

        <el-button type="primary" style="margin: 0 auto;text-align: center;display: block;" @click="onUpdate">修改预约</el-button>
      </el-form>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="evaluateOpen" width="500px" append-to-body>
      <el-form   ref="form" :model="evaluate" label-width="auto">
        <el-form-item label="医生名称：">
          <el-input readonly style="width: 300px" v-model="evaluate.name"></el-input>
        </el-form-item>

        <el-form-item label="请输入评价内容：">
          <el-input :readonly="vieweValuate" style="width: 300px"  type="textarea" v-model="evaluate.desc"></el-input>
        </el-form-item>
        <el-form-item label="请进行评分：">
        <el-rate
          v-model="evaluate.servicePoint"
          show-score
          :disabled="vieweValuate"
          text-color="#ff9900"
          score-template="{value}">
        </el-rate>
        </el-form-item>

        <el-button type="primary" v-if="!vieweValuate" style="margin: 0 auto;text-align: center;display: block;" @click="submitComment">确定评分</el-button>
      </el-form>
    </el-dialog>

    <el-dialog title="就诊单信息" :visible.sync="recodeOpen" width="500px" append-to-body>
      <el-form   ref="form" :model="evaluate" label-width="auto">
        <el-form-item label="医生名称：">
          <el-input style="width: 300px" disabled v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="预约日期：">
          <el-col :span="11">
            <el-date-picker type="date" disabled  value-format="yyyy-MM-dd" @change="changeDate" :picker-options="pickerOptions" placeholder="选择日期" v-model="form.appointmentDate" style="width: 300px;"></el-date-picker>
          </el-col>

        </el-form-item>
        <el-form-item label="预约时间段：">
          <el-select  style="width: 300px"  disabled clearable v-model="form.slot" placeholder="请选择时间段">
            <el-option v-if="morning" label="上午" value="0"></el-option>
            <el-option v-if="afternoon" label="下午" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="病情描述" prop="describe">
          <el-input
            v-model="form.describe"
            placeholder="请输入病情描述"
            maxlength="30"
            disabled
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="开药信息" prop="drugInformation">
          <el-input
            v-model="form.drugInformation"
            placeholder="请输入开药信息"
            maxlength="30"
            disabled
            type="textarea"
          />
        </el-form-item>
        <el-form-item  v-if="showImg" label="就诊图片">
          <el-image  :src="imgSrc">
          </el-image>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
      <el-button type="warning"  @click="downloadPdf">下载</el-button>
      <el-button type="primary"  @click="hideDetails">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getAppointmentLog,
  cancelAppointmentLog,
  getDateAppointmentInfo,
  getDoctorLeaveInfo,
  updateAppointmentInfo,
  submitComment,
  getCommentById, getVisitRecode, download,downloadPdf
} from '@/api/appointment'
export default {
  name: 'AppointmentLog',
  data () {
    const self = this
    return {
      logList: [],
      index: '0',
      queryHaveParams: {
        pageNum: 1,
        pageSize: 3
      },
      queryCompleteParams: {
        pageNum: 1,
        pageSize: 3
      },
      queryCancelParams: {
        pageNum: 1,
        pageSize: 3
      },
      currentPage: 1,
      form: {
        id: null,
        name: '',
        appointmentDate: null,
        slot: '',
        desc: '',
        doctorId: ''
      },
      evaluate: {
        id: 0,
        name: '',
        desc: '',
        servicePoint: 0
      },
      vieweValuate: false,
      evaluateOpen: false,
      haveingTotal: 0,
      completeTotal: 0,
      cancelTotal: 0,
      currentCompletePage: 0,
      currentCancelPage: 0,
      leaveList: [],
      cancelList: [],
      showImg: false,
      open: false,
      recodeOpen: false,
      imgSrc: undefined,
      loading: true,
      completeList: [],
      morning: true,
      afternoon: true,
      title: '',
      id:undefined,
      pickerOptions: {
        disabledDate (time) {
          const dayOfWeek = time.getDay()
          if (self.compare(time.getTime(), Date.now())) {
            return time.getTime() < Date.now()
          } else if (dayOfWeek === 0 || dayOfWeek === 6) {
            // 如果是周六或周日，禁用该日期
            return true
          } else if (self.compareLeave(time)) {
            return true
          }
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  methods: {
    compareLeave (time) {
      const dateStr = this.dateToString(time)
      for (let i = 0; i < this.leaveList.length; i++) {
        if (time.getTime() == this.leaveList[i]) {
          return true
        }
      }
    },
    handlerEvaluate (item) {
      this.evaluateOpen = true
      this.evaluate.name = item.name
      this.evaluate.servicePoint = 0
      this.evaluate.desc = ''
      this.evaluate.id = item.id
      this.title = '进行评价'
      this.vieweValuate = false
    },
    routeChange () {
      const that = this
      if (this.index === '0') {
        getAppointmentLog(that.index, that.queryHaveParams).then((response) => {
          that.haveingTotal = response.total
          that.logList = response.list
        }).catch(() => {

        })
      }
      if (this.index === '1') {
        getAppointmentLog(that.index, that.queryCompleteParams).then((response) => {
          that.completeTotal = response.total
          that.completeList = response.list
        }).catch(() => {

        })
      }
      if (this.index === '2') {
        getAppointmentLog(that.index, that.queryCancelParams).then((response) => {
          that.cancelTotal = response.total
          that.cancelList = response.list
        }).catch(() => {

        })
      }
    },
    viewEvaluate (item) {
      this.evaluateOpen = true
      this.evaluate.name = item.name
      this.evaluate.id = item.id,
      this.title = '查看评价',
      this.vieweValuate = true,
      getCommentById(this.evaluate.id).then((response) => {
        this.evaluate.servicePoint = response.servicePoint
        this.evaluate.desc = response.content
      }).catch(() => {

      })
    },
    submitComment () {
      const that = this
      if (this.evaluate.desc === '') {
        that.$message({
          type: 'error',
          message: '请输入评分内容!'
        })
        return
      }
      if (this.evaluate.servicePoint === 0) {
        that.$message({
          type: 'error',
          message: '请进行评分!'
        })
        return
      };
      submitComment(that.evaluate).then((response) => {
        that.$alert('你已成功评价', '评价成功', {
          confirmButtonText: '确定',
          type: 'success'
        }).then(() => {
          that.evaluateOpen = false
          that.routeChange()
        })
      }).catch(() => {

      })
      console.log(this.evaluate)
    },
    downloadPdf(){
      downloadPdf(this.form.id).then((response) => {

      })
    },
    handleSizeChange (newSize) {
      const that = this
      console.log(newSize)
      that.queryHaveParams.pageSize = newSize
      getAppointmentLog(that.index, that.queryHaveParams).then((response) => {
        that.haveingTotal = response.total
        that.logList = response.list
      }).catch(() => {

      })
    },
    handleCancelSizeChange (newSize) {
      const that = this
      console.log(newSize)
      that.queryCancelParams.pageSize = newSize
      getAppointmentLog(that.index, that.queryCancelParams).then((response) => {
        that.cancelTotal = response.total
        that.cancelList = response.list
      }).catch(() => {

      })
    },
    // 监听页码值变化
    handleCancelCurrentChange (newPage) {
      const that = this
      console.log(newPage)
      that.queryCancelParams.pageNum = newPage
      getAppointmentLog(that.index, that.queryCancelParams).then((response) => {
        that.cancelTotal = response.total
        that.cancelList = response.list
      }).catch(() => {

      })
    },
    handleCompleteSizeChange (newSize) {
      const that = this
      console.log(newSize)
      that.queryCompleteParams.pageSize = newSize
      getAppointmentLog(that.index, that.queryCompleteParams).then((response) => {
        that.completeTotal = response.total
        that.completeList = response.list
      }).catch(() => {

      })
    },
    // 监听页码值变化
    handleCompleteCurrentChange (newPage) {
      const that = this
      console.log(newPage)
      that.queryCompleteParams.pageNum = newPage
      getAppointmentLog(that.index, that.queryCompleteParams).then((response) => {
        that.completeTotal = response.total
        that.completeList = response.list
      }).catch(() => {

      })
    },
    // 监听页码值变化
    handleCurrentChange (newPage) {
      const that = this
      console.log(newPage)
      that.queryHaveParams.pageNum = newPage
      getAppointmentLog(that.index, that.queryHaveParams).then((response) => {
        console.log(response)
        that.haveingTotal = response.total
        that.logList = response.list
      }).catch(() => {
      })
    },
    onUpdate () {
      const that = this
      if (that.form.appointmentDate == null) {
        that.$message({
          type: 'error',
          message: '清选择预约日期!'
        })
        return
      }

      if (that.form.slot == '') {
        that.$message({
          type: 'error',
          message: '清选择预约时间段!'
        })
        return
      }

      updateAppointmentInfo(that.form).then((response) => {
        that.open = false
        const time = that.form.slot === '0' ? '上午' : '下午'
        that.$alert('你已成功修改预约，新的预约时间是：' + that.form.appointmentDate + '的' + time + '时间段', '修改成功', {
          confirmButtonText: '确定',
          type: 'success'
        }).then(() => {
          that.routeChange()
        })
      }).catch(() => {

      })
    },
    handleClick (tab, event) {
      this.routeChange()
    },
    handleUpdate (item) {
      this.open = true
      console.log(item.id)
      this.form.name = item.name
      this.form.id = item.id
      this.form.slot = item.slot === '上午' ? '0' : '1'
      this.form.desc = item.detailDesc
      this.form.appointmentDate = item.appointmentDate
      this.form.doctorId = item.doctorId
      getDoctorLeaveInfo(item.doctorId).then((response) => {
        this.leaveList = response
        this.loading = false
      }).catch(() => {
      })
    },
    hideDetails () {
      this.recodeOpen = false
      this.showImg = false
      this.form.name = undefined
      this.form.id = undefined
      this.form.slot = undefined
      this.form.appointmentDate = undefined
      this.form.doctorId = undefined
      this.form.describe = undefined
      this.form.drugInformation = undefined
      this.imgSrc = undefined
    },
    showDetails (item) {
      console.log(item)
      this.recodeOpen = true
      this.form.name = item.name
      this.form.id = item.id
      this.form.slot = item.slot === '上午' ? '0' : '1'
      this.form.appointmentDate = item.appointmentDate
      this.form.doctorId = item.doctorId
      this.showImg = false
      // 得到信息
      getVisitRecode(item.id).then((response) => {
        console.log(response)
        this.form.describe = response.describe
        this.form.drugInformation = response.drugInformation
        if (response.filepath == null) {
          this.showImg = false
        }
        download(response.filepath).then((response) => {
          this.showImg = true
          const url = window.URL.createObjectURL(response)
          this.imgSrc = url
        }).catch(() => {

        })
      }).catch(() => {

      })
    },
    changeDate () {
      const date = this.dateToString(new Date())
      if (this.form.date === date) {
        if (date > 12) {
          this.morning = false
        }
      };
      this.form.slot = ''
      const that = this
      getDateAppointmentInfo(this.form.doctorId, this.form.appointmentDate).then((response) => {
        if (response.morningNumber <= 0) {
          that.morning = false
        } if (response.afternoonNumber <= 0) {
          that.afternoon = false
        }
      }).catch(() => {

      })
    },
    compare (date, date1) {
      const dateStr = this.dateToString(date)
      const dateStr1 = this.dateToString(date1)
      if (dateStr === dateStr1) {
        if (new Date(date1).getHours() > 18) {
          return true
        }
      }
    },
    dateToString (dateTime) {
      dateTime = new Date(dateTime)
      // 获取年份
      const Y = dateTime.getFullYear() + '-'
      // 获取当前年的月份 月份要 + 1 （0代表1月）date.getMonth() + 1
      const M = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) + '-' : (dateTime.getMonth() + 1) + '-'
      // 获取当前日（1 - 31）
      const D = dateTime.getDate() < 10 ? '0' + (dateTime.getDate()) : (dateTime.getDate())

      return Y + M + D
    },

    handleCancel (item) {
      const that = this
      this.$confirm('是否取消' + item.appointmentDate + '号' + item.slot + '"的预约?', '取消提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelAppointmentLog(item.id).then((response) => {
          that.$message({
            type: 'success',
            message: '取消成功!'
          })
          this.routeChange()
        }).catch(() => {

        })
      }).catch(() => {})
    }
  },
  created () {
    this.routeChange()
  }
}
</script>

<style scoped>
.container {
  padding-top: 10px;
}

.card-body .rounded-circle {
  margin-bottom: 15px;
  box-shadow: 0 2px 6px #e6ecf1;
}
.card {
  border-radius: 3px;
  border: none;
  position: relative;
  margin-bottom: 30px;
}

.card {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-clip: border-box;

  border-radius: 0.25rem;
}

.card-body {
  background-color: #fff;
  padding-top: 20px;
  padding-bottom: 20px;
  padding: 20px 25px;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 1.25rem;
  margin-bottom: 15px;
}

.media {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: start;
  align-items: flex-start;
}

.media .media-title {
  margin-top: 0;
  margin-bottom: 5px;
  font-weight: 600;
  font-size: 15px;
  color: #34395e;
}
.media-body {
  -ms-flex: 1;
  flex: 1;
}

.media .media-items .media-item {
  flex: 1;
  text-align: center;
  padding: 0 15px;
}

.media .media-items .media-item .media-label {
  font-weight: 600;
  font-size: 12px;
  color: #34395e;
  letter-spacing: .5px;
}

/deep/ .el-rate__icon {
  font-size: 30px;
}
</style>
